package com.techblor.wechat.library.api;

import com.alibaba.fastjson.JSON;
import com.techblor.wechat.library.bean.wxacode.UnlimitWxaCodeParams;
import com.techblor.wechat.library.bean.wxacode.WxaCode;
import com.techblor.wechat.library.bean.wxacode.WxaCodeParams;
import com.techblor.wechat.library.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;

import java.awt.image.BufferedImage;

/**
 * 微信小程序码api
 */
@Slf4j
public class WxacodeApi extends WechatApi {

    /**
     * 获取小程序二维码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制,详见获取二维码。
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
     *
     * @param params
     * @param accessToken
     * @return
     */
    public WxaCode createQRCode(WxaCodeParams params, String accessToken) {
        String url = BASE_URI + "/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
        String result = HttpClientUtil.doPostJson(url, JSON.toJSONString(params));
        return JSON.parseObject(result, WxaCode.class);
    }

    /**
     * 获取小程序码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制,详见获取二维码。
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
     *
     * @param params
     * @param accessToken
     * @return
     */
    public WxaCode getWxacode(WxaCodeParams params, String accessToken) {
        String url = BASE_URI + "/wxa/getwxacode?access_token=" + accessToken;
        BufferedImage bufferedImage = HttpClientUtil.sendPostJson(url, JSON.toJSONString(params));
        if (null == bufferedImage) {
            return null;
        }

        WxaCode wxaCode = new WxaCode();
        wxaCode.setContentType("image/jpeg");
        wxaCode.setBuffer(bufferedImage);
        return wxaCode;
    }

    /**
     * 获取小程序码,适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制。更多用法详见 获取二维码。
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
     *
     * @param params
     * @param accessToken
     * @return
     */
    public WxaCode getUnlimited(UnlimitWxaCodeParams params, String accessToken) {
        String url = BASE_URI + "/wxa/getwxacodeunlimit?access_token=" + accessToken;
        BufferedImage bufferedImage = HttpClientUtil.sendPostJson(url, JSON.toJSONString(params));
        if (null == bufferedImage) {
            return null;
        }

        WxaCode wxaCode = new WxaCode();
        wxaCode.setContentType("image/jpeg");
        wxaCode.setBuffer(bufferedImage);
        return wxaCode;
    }
}
